<template>
  <div class="dialog-index-img">
    <el-dialog
      v-model="visible"
      :title="!dataForm.imgId ? $t('crud.addTitle') : $t('crud.updateBtn')"
      :close-on-click-modal="false"
      @close="onCloseDialogHandle"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataRule"
        label-width="135px"
        @submit.prevent
      >
        <el-form-item
          :label="$t('admin.carouselImg')"
          prop="imgUrl"
        >
          <!-- img-upload组件 -->
          <img-upload
            ref="nowImg"
            v-model="dataForm.imgUrl"
          />
          <div>
            <span v-if="dataForm.imgType === 0">{{ $t('admin.recommImgSize') }}750*400</span>
            <span v-if="dataForm.imgType === 1">{{ $t('admin.recommImgSize') }}1920*450</span>
          </div>
        </el-form-item>
        <el-form-item
          :label="$t('temp.sequence')"
          prop="seq"
        >
          <el-input
            v-model="dataForm.seq"
            type="number"
            min="0"
            max="2147483640"
            @change="onSeqCheck"
          />
        </el-form-item>
        <el-form-item
          :label="$t('product.status')"
          prop="status"
        >
          <el-radio-group v-model="dataForm.status">
            <el-radio :label="0">
              {{ $t('publics.disable') }}
            </el-radio>
            <el-radio :label="1">
              {{ $t('publics.normal') }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :label="$t('platform.client')"
          prop="imgType"
        >
          <el-radio-group v-model="dataForm.imgType">
            <el-radio :label="0">
              {{ $t('platform.mobile') }}
            </el-radio>
            <el-radio :label="1">
              {{ $t('platform.pc') }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :label="$t('publics.type')"
          prop="type"
        >
          <el-radio-group v-model="dataForm.type">
            <el-radio :label="-1">
              {{ $t('productComm.no') }}
            </el-radio>
            <el-radio :label="0">
              {{ $t('home.product') }}
            </el-radio>
          </el-radio-group>
          <div v-if="dataForm.type === 0 && dataForm.relation != null">
            <el-card
              :body-style="{ padding: '0px' }"
              class="index-image-prod-card"
              style="height: 160px; width: 120px"
            >
              <!-- todo: 商品已下架时展示状态 -->
              <div
                v-if="false"
                class="card-prod-status-tips"
              >
                {{ $t('publics.hadLowerShelf') }}
              </div>
              <!-- prod-pic组件 -->
              <prod-pic
                height="104px"
                width="100%"
                :pic="card.pic"
                class="box"
              />
              <div class="card-prod-info-btn">
                <div class="prod-name">
                  {{ card.name }}
                </div>
                <div class="del-btn">
                  <span @click="onDelPord">{{ $t('text.delBtn') }}</span>
                </div>
              </div>
            </el-card>
          </div>
          <div v-if="dataForm.relation == null">
            <el-button
              v-if="dataForm.type === 0"
              @click="onAddProd"
            >
              {{
                $t('product.select')
              }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div
            class="default-btn"
            @click="visible = false"
          >
            {{ $t('crud.filter.cancelBtn') }}
          </div>
          <div
            class="primary-btn default-btn"
            @click="onSubmit()"
          >
            {{ $t('crud.filter.submitBtn') }}
          </div>
        </div>
      </template>
    </el-dialog>
    <!-- 商品选择弹窗-->
    <prods-select
      v-if="prodsSelectVisible"
      ref="prodsSelectRef"
      :is-single="true"
      @refresh-select-prods="onSelectIndexProd"
    />
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'

const dataRule = {
  imgUrl: [{ required: true, message: $t('admin.carouselImgNoNull'), trigger: 'blur' }],
  seq: [{ required: true, message: $t('admin.seqNONull'), trigger: 'blur' }]
}
const emit = defineEmits(['refreshDataList'])
const dataForm = ref({
  status: 1,
  des: '',
  imgUrl: '',
  imgType: 0,
  seq: 0,
  imgId: 0,
  type: -1,
  relation: null
})
const validPic = ref(false)
const dataFormRef = ref(null)

// 获取分类数据
// 关联数据
const card = ref({
  id: 0,
  pic: '',
  name: '',
  realData: {
    prod: [],
    shop: [],
    activity: []
  }
})
const prodsSelectVisible = ref(false)
const visible = ref(false)
const init = id => {
  validPic.value = false // 初始化不验证是否选择图片
  visible.value = true
  dataForm.value.imgId = id || 0
  nextTick(() => {
    prodsSelectVisible.value = false
    dataFormRef.value.resetFields()
  })
  if (dataForm.value.imgId) {
    // 获取产品数据
    http({
      url: http.adornUrl(`/admin/indexImg/info/${dataForm.value.imgId}`),
      method: 'get',
      params: http.adornParams()
    }).then(({ data }) => {
      dataForm.value = data
      if (data.relation) {
        card.value.pic = data.pic
        card.value.name = data.prodName
        card.value.id = data.relation
      }
    })
  } else {
    nextTick(() => {
      dataFormRef.value.resetFields()
      dataForm.value.imgUrl = ''
      dataForm.value.relation = null
    })
  }
}
// 检验输入顺序值
const onSeqCheck = () => {
  let maxNum = Math.round(dataForm.value.seq)
  if (!maxNum) {
    maxNum = 0
  } else if (maxNum < 0) {
    maxNum = 0
  } else if (maxNum > 2147483640) {
    maxNum = 2147483640
  }
  dataForm.value.seq = maxNum
}
// 表单提交
const isSubmit = ref(true)
const page = {
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
}
const onSubmit = () => {
  validPic.value = true // 用于解决选择图片提示不隐藏问题
  if (dataForm.value.type === 0 && dataForm.value.relation == null) {
    ElMessage({
      message: $t('marketing.pleaseSelectAProduct'),
      type: 'error',
      duration: 1500
    })
    return
  }
  if (dataForm.value.type === -1) {
    dataForm.value.relation = null
  }
  dataFormRef.value.validate(() => {
    if (!dataForm.value.imgUrl) {
      return
    }
    if (!isSubmit.value) {
      return true
    }
    isSubmit.value = false
    const param = dataForm.value
    http({
      url: http.adornUrl('/admin/indexImg'),
      method: param.imgId ? 'put' : 'post',
      data: http.adornData(param)
    }).then(() => {
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          isSubmit.value = true
          visible.value = false
          emit('refreshDataList', page)
        }
      })
    }).catch(() => {
      isSubmit.value = true
    })
  })
}
const onDelPord = () => {
  dataForm.value.relation = null
}
// 打开选择商品
const prodsSelectRef = ref(null)
const onAddProd = () => {
  prodsSelectVisible.value = true
  nextTick(() => {
    prodsSelectRef.value.init(card.value.realData.prod)
  })
}
// 添加指定商品
const onSelectIndexProd = prods => {
  card.value.realData.prods = prods
  if (prods.length) {
    const selectProd = prods[0]
    dataForm.value.relation = selectProd.prodId
    card.value.pic = selectProd.pic
    card.value.name = selectProd.prodName
    card.value.id = selectProd.prodId
  } else {
    card.value = {}
    dataForm.value.relation = null
  }
}
// 关闭对话框回调
const nowImg = ref(null)
const onCloseDialogHandle = () => {
  prodsSelectVisible.value = false
  dataFormRef.value.resetFields()
  nowImg.value.detailImg()
  dataForm.value.relation = null
  card.value = {
    id: 0,
    pic: '',
    name: '',
    realData: {
      prod: [],
      shop: [],
      activity: []
    }
  }
}
defineExpose({ init })
</script>
<style lang="scss" scoped>
.dialog-index-img {
  .index-image-prod-card {
    position: relative;
    .card-prod-status-tips {
      position: absolute;
      right: 0;
      bottom: 54px;
      color: #fff;
      font-size: 12px;
      line-height: 16px;
      background-color: rgba(0, 0, 0, 0.3);
      padding: 3px 6px;
      border-top-left-radius: 4px;
    }
  }
  :deep(.el-form-item__content) {
    display: block;
  }
}
</style>
